using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.GamePlay;
using System.Collections.Generic;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 改变实体激活状态
    /// 参数：
    /// args1：1：tag（0表示自己），2：是否激活（0：不激活，1：激活），3：激活时默认动作，4：是否改变y轴旋转，5：激活时的y轴旋转
    /// args2：1:x, 2:y, 3:z
    /// </summary>
    public class ExecChangeEntityActivation : BaseServiceExecution
    {
        public override void Execute(LevelRegion region, LevelPlayer player)
        {
            var config = _config as ExecParamChangeEntityActivation;
            var entities = ListPool<LevelEntity>.Get();
            if (!LgLevelEntityUtil.GetEntitiesByDynCfgKeys(region, triggerEntity, config.tagOrMcid, entities, true))
            {
                ListPool<LevelEntity>.Put(entities);
                return;
            }
            if (config.pos != Vector3Int.zero && entities.Count > 1)
            {
                List<int> ids = entities.ConvertAll(entity => entity.entityConfig.id);
                LogicLog.LogError($"不能在激活多个实体时同时改变位置。触发源实体：{triggerEntity?.entityConfig.id}，尝试修改的实体：{string.Join(',', ids)}");
                ListPool<LevelEntity>.Put(entities);
                return;
            }

            int animActionId = config.animActionId;
            if (animActionId != 0)
            {
                LogicLog.LogError($"改变实体激活状态改版后暂不支持animActionId，有需求请找程序商量重新设计代码逻辑。" +
                    $"\n（目前实体激活和失活客户端会当做“出生和死亡”处理，和何平对过，策划也只会使用停用和重启的思路来配置，" +
                    $"而不是暂停和恢复）");
                //不用return，忽略该参数即可
            }

            bool isActive = config.isActive;
            bool isSetRotation = config.isSetRotation;
            int rotationY = config.rotationY;
            List<LevelEntity> changedEntities = ListPool<LevelEntity>.Get();
            {
                foreach (LevelEntity entity in entities)
                {
                    bool changed = entity.SetActive(isActive);
                    if (isSetRotation)
                    {
                        entity.SetRotationY(rotationY, false);
                    }
                    if (changed || isSetRotation) //只有变化了的才发给视图层
                    {
                        changedEntities.Add(entity);
                    }
                }
                if (isActive)
                {
                    region.UpdateEntities(player, changedEntities);
                }
                else
                {
                    region.UpdateRemoveEntities(player, changedEntities);
                }
                ListPool<LevelEntity>.Put(changedEntities);
            } // release changedEntities

            if (config.pos != Vector3Int.zero)
            {
                LevelEntity entity = entities[0]; //只支持一个实体在改变状态后寻路
                entity.MoveInNavMesh(config.pos, entity.buffSpeedRatio, true, EntityMoveDirType.KeepRotation);
            }

            ListPool<LevelEntity>.Put(entities);
        }
    }
}
